package com.meow_woof.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.meow_woof.dto.Result;
import com.meow_woof.dto.UserDTO;
import com.meow_woof.entity.Follow;
import com.meow_woof.mapper.FollowMapper;
import com.meow_woof.service.IFollowService;
import com.meow_woof.service.IUserService;
import com.meow_woof.utils.UserHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 服务实现类
 */
@Service
public class FollowServiceImpl extends ServiceImpl<FollowMapper, Follow> implements IFollowService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private IUserService userService;
    public Result follow(Long id, Boolean isFollow) {
        Long userId = UserHolder.getUser().getId();
        String key="follows:"+userId;


        if (isFollow) {
            Follow follow = Follow.builder()
                    .userId(userId)
                    .followUserId(id)
                    .build();
            boolean save = save(follow);
            if (save) {
                stringRedisTemplate.opsForSet().add(key,id.toString());
            }

        }else{
            boolean remove = remove(new QueryWrapper<Follow>()
                    .eq("user_id", userId).eq("follow_user_id", id));
            if (remove) {
                stringRedisTemplate.opsForSet().remove(key,id.toString());
            }


        }
        return Result.ok();
    }

    public Result isfollow(Long id) {
        Long userId = UserHolder.getUser().getId();
        Long count = query().eq("user_id", userId).eq("follow_user_id", id).count();
        return Result.ok(count>0);
    }

    public Result followCommons(Long id) {
        Long userId = UserHolder.getUser().getId();
        String key1="follows:"+id;
        String key2="follows:"+userId;

        Set<String> intersect = stringRedisTemplate.opsForSet().intersect(key1, key2);
        if(intersect==null|| intersect.isEmpty()){
            return  Result.ok(Collections.emptyList());
        }
        List<Long> list = intersect.stream().map(Long::valueOf).collect(Collectors.toList());
        List<UserDTO> userDTOS = userService.listByIds(list).stream().map(user ->
                BeanUtil.copyProperties(user, UserDTO.class)).toList();
        return Result.ok(userDTOS);



    }
}
